<template>
	<view class="message-page">
		<!-- 消息分类Tab -->
		<view class="message-tabs">
			<view 
				v-for="tab in tabs" 
				:key="tab.type" 
				class="tab-item" 
				:class="{ active: activeTab === tab.type }"
				@click="handleTabChange(tab.type)"
			>
				<text class="tab-label">{{ tab.label }}</text>
				<view v-if="tab.unreadCount > 0" class="badge">{{ tab.unreadCount > 99 ? '99+' : tab.unreadCount }}</view>
			</view>
		</view>

		<!-- 操作栏 -->
		<view class="action-bar" v-if="messageList.length > 0">
			<text class="unread-tip">未读消息：{{ currentUnreadCount }}</text>
			<view class="mark-read-btn" @click="handleMarkAllRead">
				<up-icon name="checkbox-mark" size="16" color="#667eea"></up-icon>
				<text class="mark-text">全部标记已读</text>
			</view>
		</view>

		<!-- 消息列表 -->
		<scroll-view 
			class="message-list" 
			scroll-y 
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
			@scrolltolower="onLoadMore"
		>
			<!-- 消息项 -->
			<view 
				v-for="message in messageList" 
				:key="message.messageId"
				class="message-item"
				:class="{ unread: message.isRead === 0 }"
				@click="handleMessageClick(message)"
			>
				<!-- 未读标识 -->
				<view class="unread-dot" v-if="message.isRead === 0"></view>

				<!-- 消息图标/头像 -->
				<view class="message-icon">
					<up-image 
						v-if="message.senderAvatar" 
						:src="message.senderAvatar" 
						width="90rpx" 
						height="90rpx" 
						shape="circle"
					></up-image>
					<view v-else class="icon-wrapper" :class="`icon-${message.type}`">
						<up-icon :name="getMessageIcon(message.type)" size="28" color="#ffffff"></up-icon>
					</view>
				</view>

				<!-- 消息内容 -->
				<view class="message-content">
					<view class="message-header">
						<text class="message-title">{{ message.title }}</text>
						<text class="message-time">{{ formatTime(message.createTime) }}</text>
					</view>
					<text class="message-desc">{{ message.content }}</text>
					<text v-if="message.relatedTitle" class="related-title">相关：{{ message.relatedTitle }}</text>
				</view>

				<!-- 箭头 -->
				<up-icon name="arrow-right" size="16" color="#cccccc" class="arrow-icon"></up-icon>
			</view>

			<!-- 空状态 -->
			<view v-if="!loading && messageList.length === 0" class="empty-state">
				<up-icon name="bell" size="80" color="#cccccc"></up-icon>
				<text class="empty-text">暂无{{ currentTabLabel }}消息</text>
			</view>

			<!-- 加载状态 -->
			<view v-if="loading" class="loading-state">
				<up-loading-icon></up-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 没有更多 -->
			<view v-if="!loading && hasMore === false && messageList.length > 0" class="no-more">
				—— 没有更多了 ——
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
import { getMessages, markAllAsRead, getUnreadCount } from '../../server/api/message.js';
import showToast from '../../utils/showToast.js';
import { formatRelativeTime } from '../../utils/date.js';

// Tab 配置（移除了全部分类）
const tabs = ref([
	{ type: 'reply', label: '回复', unreadCount: 0 },
	{ type: 'system', label: '系统', unreadCount: 0 },
	{ type: 'official', label: '官方', unreadCount: 0 },
	{ type: 'activity', label: '活动', unreadCount: 0 },
	{ type: 'other', label: '其它', unreadCount: 0 }
]);

// 当前激活的Tab（默认第一个）
const activeTab = ref('reply');

// 消息列表
const messageList = ref([]);

// 加载状态
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);

// 分页参数
const pageParams = reactive({
	pageNum: 1,
	pageSize: 20
});

// 当前Tab的未读数量
const currentUnreadCount = computed(() => {
	const tab = tabs.value.find(t => t.type === activeTab.value);
	return tab ? tab.unreadCount : 0;
});

// 当前Tab的标签文字
const currentTabLabel = computed(() => {
	const tab = tabs.value.find(t => t.type === activeTab.value);
	return tab ? tab.label : '';
});

/**
 * 获取消息图标
 */
const getMessageIcon = (type) => {
	const iconMap = {
		reply: 'chat',
		system: 'setting',
		official: 'account',
		activity: 'calendar',
		other: 'bell'
	};
	return iconMap[type] || 'bell';
};

/**
 * 格式化时间
 */
const formatTime = (timestamp) => {
	return formatRelativeTime(timestamp);
};

/**
 * 切换Tab
 */
const handleTabChange = (type) => {
	if (activeTab.value === type) return;
	
	activeTab.value = type;
	pageParams.pageNum = 1;
	messageList.value = [];
	hasMore.value = true;
	loadMessages();
};

/**
 * 加载消息列表
 */
const loadMessages = async (showLoading = true) => {
	if (loading.value) return;

	try {
		if (showLoading) {
			loading.value = true;
		}

		const params = {
			type: activeTab.value,
			pageNum: pageParams.pageNum,
			pageSize: pageParams.pageSize
		};

		const res = await getMessages(params);

		if (res.code === 200) {
			const newList = res.data.list || [];
			
			if (pageParams.pageNum === 1) {
				messageList.value = newList;
			} else {
				messageList.value.push(...newList);
			}

			// 判断是否还有更多
			hasMore.value = newList.length >= pageParams.pageSize;
		}
	} catch (error) {
		console.error('加载消息失败:', error);
		showToast('加载失败，请重试', 'error');
	} finally {
		loading.value = false;
		refreshing.value = false;
	}
};

/**
 * 加载未读数量
 */
const loadUnreadCount = async () => {
	try {
		const res = await getUnreadCount();
		if (res.code === 200) {
			const counts = res.data;
			tabs.value[0].unreadCount = counts.reply;
			tabs.value[1].unreadCount = counts.system;
			tabs.value[2].unreadCount = counts.official;
			tabs.value[3].unreadCount = counts.activity;
			tabs.value[4].unreadCount = counts.other;
		}
	} catch (error) {
		console.error('加载未读数量失败:', error);
	}
};

/**
 * 下拉刷新
 */
const onRefresh = () => {
	refreshing.value = true;
	pageParams.pageNum = 1;
	hasMore.value = true;
	loadMessages(false);
	loadUnreadCount();
};

/**
 * 上拉加载更多
 */
const onLoadMore = () => {
	if (!hasMore.value || loading.value) return;
	
	pageParams.pageNum++;
	loadMessages();
};

/**
 * 全部标记为已读
 */
const handleMarkAllRead = async () => {
	if (currentUnreadCount.value === 0) {
		showToast('没有未读消息', 'none');
		return;
	}

	try {
		const res = await markAllAsRead(activeTab.value);
		if (res.code === 200) {
			showToast('已标记为已读', 'success');
			
			// 更新列表中的已读状态
			messageList.value.forEach(msg => {
				msg.isRead = 1;
			});

			// 重新加载未读数量
			loadUnreadCount();
		}
	} catch (error) {
		console.error('标记失败:', error);
		showToast('操作失败', 'error');
	}
};

/**
 * 点击消息
 */
const handleMessageClick = (message) => {
	// 根据消息类型和关联类型跳转到不同页面
	if (message.relatedType === 'post' && message.relatedId) {
		// 跳转到帖子详情
		uni.navigateTo({
			url: `/pages/post/postInfo?postId=${message.relatedId}`
		});
	} else if (message.relatedType === 'activity' && message.relatedId) {
		// 跳转到活动详情
		uni.navigateTo({
			url: `/pages/activity/activityDetail?activityId=${message.relatedId}`
		});
	} else if (message.relatedType === 'user' && message.relatedId) {
		// 跳转到用户主页
		uni.navigateTo({
			url: `/pages/user/userInfo?userId=${message.relatedId}`
		});
	} else {
		// 跳转到消息详情页
		uni.navigateTo({
			url: `/pages/message/messageDetail?messageId=${message.messageId}`
		});
	}
};

// 页面加载时，可以通过参数指定初始Tab
onLoad((options) => {
	if (options.type) {
		activeTab.value = options.type;
	}
});

// 页面显示时刷新
onShow(() => {
	loadUnreadCount();
	// 如果列表不为空，刷新列表
	if (messageList.value.length > 0) {
		pageParams.pageNum = 1;
		loadMessages(false);
	}
});

// 页面加载时
onMounted(() => {
	loadMessages();
	loadUnreadCount();
});
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';

.message-page {
	min-height: 100vh;
	background: $bg-page;
	display: flex;
	flex-direction: column;
}

// Tab栏
.message-tabs {
	display: flex;
	background: $bg-card;
	padding: $spacing-lg $spacing-xl;
	border-bottom: 1px solid $border-light;
	position: sticky;
	top: 0;
	z-index: 10;

	.tab-item {
		position: relative;
		flex: 1;
		@include flex-center;
		flex-direction: column;
		padding: $spacing-sm 0;
		transition: all $transition-fast;

		.tab-label {
			font-size: $font-base;
			color: $text-secondary;
			transition: all $transition-fast;
		}

		.badge {
			position: absolute;
			top: -8rpx;
			right: 10rpx;
			min-width: 32rpx;
			height: 32rpx;
			line-height: 32rpx;
			background: $color-danger;
			color: #fff;
			font-size: 20rpx;
			text-align: center;
			border-radius: 16rpx;
			padding: 0 8rpx;
			transform: scale(0.9);
		}

		&.active {
			.tab-label {
				color: $color-primary;
				font-weight: $font-bold;
				font-size: $font-lg;
			}
		}

		&:active {
			transform: scale(0.95);
		}
	}
}

// 操作栏
.action-bar {
	@include flex-between;
	background: $bg-card;
	padding: $spacing-base $spacing-xl;
	border-bottom: 1px solid $border-light;

	.unread-tip {
		font-size: $font-sm;
		color: $text-tertiary;
	}

	.mark-read-btn {
		display: flex;
		align-items: center;
		padding: $spacing-xs $spacing-base;
		background: rgba($color-primary, 0.1);
		border-radius: $radius-sm;
		transition: all $transition-fast;

		.mark-text {
			margin-left: $spacing-xs;
			font-size: $font-sm;
			color: $color-primary;
		}

		&:active {
			transform: scale(0.95);
			opacity: 0.8;
		}
	}
}

// 消息列表
.message-list {
	flex: 1;
	height: calc(100vh - 200rpx);
}

// 消息项
.message-item {
	position: relative;
	display: flex;
	align-items: center;
	background: $bg-card;
	padding: $spacing-lg $spacing-xl;
	margin-bottom: $spacing-xs;
	transition: background $transition-fast;

	&.unread {
		background: rgba($color-primary, 0.03);
	}

	&:active {
		background: $bg-hover;
	}

	.unread-dot {
		position: absolute;
		left: $spacing-base;
		top: 50%;
		transform: translateY(-50%);
		width: 16rpx;
		height: 16rpx;
		background: $color-danger;
		border-radius: 50%;
	}

	.message-icon {
		flex-shrink: 0;
		margin-right: $spacing-lg;

		.icon-wrapper {
			width: 90rpx;
			height: 90rpx;
			@include flex-center;
			border-radius: 50%;

			&.icon-reply {
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			}

			&.icon-system {
				background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
			}

			&.icon-official {
				background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
			}

			&.icon-activity {
				background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
			}

			&.icon-other {
				background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
			}
		}
	}

	.message-content {
		flex: 1;
		min-width: 0;

		.message-header {
			@include flex-between;
			margin-bottom: $spacing-xs;

			.message-title {
				flex: 1;
				font-size: $font-base;
				font-weight: $font-medium;
				color: $text-primary;
				@include ellipsis;
			}

			.message-time {
				flex-shrink: 0;
				margin-left: $spacing-base;
				font-size: $font-xs;
				color: $text-tertiary;
			}
		}

		.message-desc {
			display: block;
			font-size: $font-sm;
			color: $text-secondary;
			line-height: $line-height-base;
			@include ellipsis(2);
			margin-bottom: $spacing-xs;
		}

		.related-title {
			display: block;
			font-size: $font-xs;
			color: $color-primary;
			@include ellipsis;
		}
	}

	.arrow-icon {
		flex-shrink: 0;
		margin-left: $spacing-base;
	}
}

// 空状态
.empty-state {
	@include flex-center;
	flex-direction: column;
	padding: 200rpx $spacing-xl;

	.empty-text {
		margin-top: $spacing-lg;
		font-size: $font-base;
		color: $text-tertiary;
	}
}

// 加载状态
.loading-state {
	@include flex-center;
	padding: $spacing-xxl;

	.loading-text {
		margin-left: $spacing-base;
		font-size: $font-sm;
		color: $text-tertiary;
	}
}

// 没有更多
.no-more {
	text-align: center;
	padding: $spacing-xxl;
	font-size: $font-sm;
	color: $text-tertiary;
}
</style>
